﻿using System;
using System.Linq;

namespace SQLPXBase.Factory.Keys.KeyModels
{
    public class StringPK:PrimaryKey
        
    {
        protected string[] keys;

        #region Constructor

        public StringPK(int keyCount)
        {
            keys = new string[keyCount];
        }

        //public StringPK(DataRow rw, string[] fieldNames, int keyCount)
        //    : base(rw, fieldNames)
        //{
        //    keys = new string[keyCount];
        //}

        #endregion

        public string[] Keys { get { return keys; } }

        public override int KeyLength
        {
            get { return keys.Length; }
        }

        public override bool IsEmpty
        {
            get { return keys.All(key => string.IsNullOrEmpty(key)); }
        }

        public override PrimaryKey DefaultValue
        {
            get { return new StringPK(keys.Length); }
        }

        public override object GetSingleValue
        {
            get
            {
                return KeyLength == 1 ? keys[0] : null;
            }
        }

        public override object[] GetValues
        {
            get
            {
                object[] tmp = new object[keys.Length];
                for (int i = 0; i < keys.Length; i++)
                {
                    string key = keys[i];
                    tmp[i] = key;
                }

                return tmp;
            }
        }

        public override void SetValues(object[] values)
        {
            CheckValues(values);

            try
            {
                for (int i = 0; i < values.Length; i++)
                {
                    object v = values[i];
                    keys[i] = (string) v;
                }
            }
            catch (Exception ex)
            {
                throw new PrimaryKeyException(ex.Message, ex);
            }
        }
    }

    public class SingleStringPK : StringPK
    {
        public SingleStringPK() : base(1) { }

        public SingleStringPK(string key) : this()
        {
            keys[0] = key;
        }

        public string Value
        {
            get { return IsEmpty ? null : keys[0]; }
            set { keys[0] = value; }
        }
    }

    public class CoupledStringPK : StringPK
    {
        public CoupledStringPK() : base(2) { }

        public CoupledStringPK(string k1, string k2) : this()
        {
            keys[0] = k1;
            keys[1] = k2;
        }

        public string Value1
        {
            get { return IsEmpty ? null : keys[0]; }
            set { keys[0] = value; }
        }

        public string Value2
        {
            get { return IsEmpty ? null : keys[1]; }
            set { keys[1] = value; }
        }
    }


}
